package com.xxx.springboot.service.impl;

import com.xxx.springboot.handler.RedisDelayQueueHandle;
import com.xxx.springboot.pojo.enums.RedisDelayQueueEnum;
import com.xxx.springboot.service.RedisDelayQueueService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

/**
 * 7. 【redis延时队列】redis 延时队列消费线程，随系统启动开启
 * CommandLineRunner实现在项目启动后执行的功能。 如果有多个需要执行的功能，而且需要按顺序执行，则添加@Order(value=1)注解。
 *
 * @author guwq
 * @since 2021/4/27
 */
@Slf4j
@Component
//@Order(value=1)
public class RedisDelayQueueRunner implements CommandLineRunner {

    @Autowired
    private RedisDelayQueueService redisDelayQueueService;

    @Override
    public void run(String... args) throws Exception {

        new Thread(
            () -> {
                while (true){
                    try {
                        // 获取redis延时队列枚举，遍历全部redis延时队列
                        RedisDelayQueueEnum[] enums = RedisDelayQueueEnum.values();
                        for (RedisDelayQueueEnum queueEnum : enums) {
                            String queueName = queueEnum.getQueueName();
                            String beanId = queueEnum.getBeanId();

                            // 从redis延时队列里获取任务信息
                            Object value = redisDelayQueueService.getTaskFromDelayQueue(queueName);
                            if(value!=null){
                                log.info("redis延时队列开始通过 beanId:{} 消费 value:{}", beanId, value);
                                // 执行任务对应的业务实现类
                                RedisDelayQueueHandle redisDelayQueueHandle = SpringUtil.getBean(queueEnum.getBeanId());
                                redisDelayQueueHandle.execute(value);
                            }
                        }
                    } catch (InterruptedException e) {
                        log.error("redis延时队列异常中断", e);
                    }
                }
            }
        ).start();
        log.info("redis延时队列启动成功");
    }
}
